package com.example.mybatis.dao.impl;

import com.example.mybatis.dao.IUserDAO;
import com.example.mybatis.pojo.User;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.Date;
import java.util.List;

public class UserDAOImpl implements IUserDAO {

    SqlSessionFactory sqlSessionFactory;

    public UserDAOImpl(SqlSessionFactory sqlSessionFactory)
    {
        this.sqlSessionFactory = sqlSessionFactory;
    }
    @Override
    public User queryUserById(int id) {
        SqlSession sqlSession=sqlSessionFactory.openSession();
        User user= (User) sqlSession.selectOne("queryUserById",1);
        System.out.println(user);
        sqlSession.close();
        return user;
    }

    @Override
    public List<User> queryUserByUsername1(String name) {
        SqlSession sqlSession=sqlSessionFactory.openSession();
        List<User> user= sqlSession.selectList("queryUserByName","%"+name+"%");
        for (Object u:user
        ) {
            System.out.println(u);
        }
        sqlSession.close();
        return user;
    }

    @Override
    public List<User> queryUserByUsername2(String name) {
        return null;
    }

    @Override
    public int saveUser(User user) {
        SqlSession sqlSession=sqlSessionFactory.openSession();
        int result=sqlSession.insert("saveuser",user);
        sqlSession.commit();
        sqlSession.close();
        System.out.println(user);
        return result;
    }

    @Override
    public int updateUserById(User user) {
        SqlSession sqlSession=sqlSessionFactory.openSession();
        int result= sqlSession.update("updateUserById",user);
        sqlSession.commit();
        sqlSession.close();
        return result;
    }

    @Override
    public int deleteUserById(int id) {
        SqlSession sqlSession=sqlSessionFactory.openSession();
        int result=sqlSession.delete("deleteUserById",id);
        sqlSession.commit();
        sqlSession.close();
        return result;
    }
}
